package cn.maihe.elg.operation.utils;

import cn.maihe.elg.operation.security.model.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @Description
 * @Author WJH
 * @Date 2021/03/26
 */
@Slf4j
public class UserContextUtil {

    /**
     * 默认运营用户的机构编码
     */
    public static final String defaultOrgCode = "-1";

    public static UserContext getUserContext() {
        try {
            Object object = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (object instanceof UserContext) {
                return ((UserContext) object);
            }
        } catch (Exception e) {
            log.error("获取userContext异常：{}", e.getMessage(),e);
        }
        //默认空上下文：兼容api接口调用时无登录状态
        return new UserContext();
    }

    public static Long getCurOrgId() {
        UserContext userContext = getUserContext();
        if (userContext == null || defaultOrgCode.equals(userContext.getOrgCode())) {
            return null;
        }
        return userContext.getOrgId();
    }

    public static String getCurUserName() {
        UserContext userContext = getUserContext();
        if (userContext == null) {
            return null;
        }
        return userContext.getUsername();
    }


}
